<template>
  <div>
    <Card :bordered="false">
      <Row>
        <Col span="12">
        <ButtonGroup>
          <Button type="primary" @click="openAddOrg">新增</Button>
        </ButtonGroup>
        </Col>
        <Col span="12" style="text-align: right">
        <Input v-model="txtSearch" placeholder="请输入机构名称" style="width: 200px"/>
        <Button icon="ios-search" type="primary" @click="getOrgList"></Button>
        </Col>
      </Row>
    </Card>
    <Card :bordered="false">
      <Table stripe height="500" :columns="columns" :data="orgList"></Table>
    </Card>
    <!--新增机构-->
    <Modal
      v-model="modal.add.status"
      :title="modal.add.title"
      :top="0" @on-cancel="modalDefineCancel('modal.add.form')">
      <Form ref= 'modal.add.form' :model="modal.add.form" :label-width="80" :rules='ruleValidate'>
        <FormItem label="机构名称" prop='orgName'>
          <Input v-model="modal.add.form.orgName" placeholder="例如：陕西瑞亚智能技术有限公司"></Input>
        </FormItem>
        <FormItem label="机构编号" prop='orgCode'>
          <Input v-model="modal.add.form.orgCode" placeholder="请输入机构编号" @on-blur="checkOrgCode(modal.add.form.orgCode)"></Input>
          <label class="codeLb" v-if="orgCodeError">机构编号已存在</label>
        </FormItem>
        <FormItem label="上级机构" prop='parentId'>
          <Select clearable v-model="modal.add.form.parentId" style="width:100%;text-align: left">
            <Option v-for="item in parentOrgList" :value="item.id" :key="item.orgName">{{ item.orgName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="机构地址" prop='address'>
          <Input v-model="modal.add.form.address" placeholder="例如：西安市高新区科技二路清华科技园"></Input>
        </FormItem>
        <FormItem label="备注">
          <Input v-model="modal.add.form.remark"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleReset('modal.add.form')">取消</Button>
        <Button type="primary" @click="handleSubmit('modal.add.form')">确定</Button>
      </div>
    </Modal>
    <!--修改机构-->
    <Modal
      v-model="modal.update.status"
      :title="modal.update.title"
      :top="0" @on-cancel="modalDefineCancel('modal.update.form')">
      <Form ref= 'modal.update.form' :model="modal.update.form" :label-width="80" :rules='ruleValidate'>
        <FormItem label="机构名称" prop='orgName'>
          <Input v-model="modal.update.form.orgName" placeholder="例如：陕西瑞亚智能技术有限公司"></Input>
        </FormItem>
        <FormItem label="机构编号" prop='orgCode'>
          <Input v-model="modal.update.form.orgCode" placeholder="请输入机构编号" @on-blur="checkOrgCode(modal.update.form.orgCode,modal.update.form.id)"></Input>
          <label class="codeLb" v-if="orgCodeError">设备编号已存在</label>
        </FormItem>
        <FormItem v-if="modal.update.form.id!='0'" label="上级机构" prop='parentId'>
          <Select clearable v-model="modal.update.form.parentId" style="width:100%;text-align: left">
            <Option v-for="item in parentOrgList" :value="item.id" :key="item.orgName">{{ item.orgName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="机构地址" prop='address'>
          <Input v-model="modal.update.form.address" placeholder="例如：西安市高新区科技二路清华科技园"></Input>
        </FormItem>
        <FormItem label="备注">
          <Input v-model="modal.update.form.remark" ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleReset('modal.update.form')">取消</Button>
        <Button type="primary" @click="handleSubmit('modal.update.form')">确定</Button>
      </div>
    </Modal>
    <!--删除机构-->
    <Modal
      v-model="modal.delete.status"
      :title="modal.delete.title">
      确定删除机构{{modal.delete.orgName}}吗？
      <div slot="footer">
        <Button type="default" @click="modal.delete.status=false">取消</Button>
        <Button type="error" @click="deleteOrg">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import urlSource from '../../api/urlSource'

  export default {
    name: "index",
    components: {},
    data() {
      let validateOrgName = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入机构名称"));
        }else{
          callback();
        }
      };
      let validateOrgCode = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入机构编号"));
        }else{
          callback();
        }
      };
      let validateParentId = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入上级机构"));
        }else{
          callback();
        }
      };
      let validateAddress = function (rule, value, callback) {
        if(!value){
          return callback(new Error("请输入机构地址"));
        }else{
          callback();
        }
      }

      return {
        parentOrgList : [],
        orgCodeError: false,
        modal: {
          add: {
            status: false,
            title: "新增机构",
            form: {
              orgCode : '',
              orgName : '',
              parentId : '',
              address: '',
              createTime: '',
              remark: '',
            }
          },
          update: {
            status: false,
            title: "修改机构",
            form: {
              id: '',
              orgCode : '',
              orgName : '',
              parentId : '',
              address: '',
              remark: '',
            }
          },
          delete: {
            status: false,
            title: "系统提示",
            accountName: "",
            id: ""
          }
        },
        txtSearch: "",
        columns: [
          {
            type: 'index',
            width: 60,
            align: 'center'
          },
          {
            title: '机构名称',
            key: 'orgName'
          },
          {
            title: '机构编号',
            key: 'orgCode'
          },
          {
            title: '机构地址',
            key: 'address'
          },
          {
            title: '上级机构',
            key: 'parentId',
            render: (h, params) => {
              let parentOrgName = '';
              /* 如果机构id 为0,则展示根机构 */
              if(params.row.parentId == '-1'){
                // parentOrgName = '陕西瑞亚';
                parentOrgName = '';
              }else{
                this.parentOrgList.forEach((data) => {
                  if(params.row.parentId == data.id){
                    parentOrgName = data.orgName;
                  }
                })
              }
              return h('div',[
                h('div', parentOrgName)
              ]);
            }
          },
          {
            title: '创建时间',
            key: 'createTime'
          },
          {
            title: '操作',
            width: 280,
            key: 'id',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.modal.update.status = true;
                      this.modal.update.form = JSON.parse(JSON.stringify(params.row));
                    }
                  }
                }, '修改'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.deleteOrgBefore(params.row);
                    }
                  },
                  style: {
                    display: params.row.id == 0 ? "none" : (params.row.parentId == -1 || params.row.parentId == 0) && this.$store.state.user.superFlag == 0 ? "none" : "inline-block"
                  }
                }, '删除')
              ]);
            }
          },
        ],
        orgList: [],
        ruleValidate:{
          orgName : [{required: true,validator: validateOrgName,trigger: 'blur'}],
          orgCode : [{required: true,validator: validateOrgCode,trigger: 'blur'}],
          parentId : [{required: true,validator: validateParentId,type: 'string', message: '请选择机构',trigger: 'change'}],
          address : [{required: true,validator: validateAddress,trigger: 'blur'}],
        },
      }
    },
    methods: {
      handleReset (name) {
        if(name=='modal.add.form'){
          this.modal.add.status=false;
        }else{
          this.modal.update.status=false;
        }
        this.orgCodeError = false;
        this.$refs[name].resetFields();
      },
      modalDefineCancel (name){
        this.orgCodeError = false;
        this.$refs[name].resetFields();
      },
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            if(this.orgCodeError){
              this.$Message.error('请正确填写机构编号');
              return;
            }
            if(name=='modal.add.form'){//添加表单校验
              this.addOrg();
            }else{//修改表单校验
              this.updateOrg();
            }
          } else {
            this.$Message.error('请正确填写信息');
          }
        })
      },
      //获取上级机构
      getCurrentParentOrg(currentLoginOrgId){
        let url = '';
        if(this.$store.state.user.orgId == 0){
          //超级管理登录显示顶级机构以及子机构
          url = urlSource.apiUrl + 'org/getAll/';
          this.$http.get(url).then(res => {
            this.parentOrgList = res.data;
          }).catch(err => {
          })
        }else{
          //如果是企业管理员登录显示该机构和子机构
          url = urlSource.apiUrl + 'org/getParentOrg/'+currentLoginOrgId;
          this.$http.get(url).then(res => {
            if(res.data){
              let parentId = '';
              res.data.forEach(v => {
                if(v.parentId == '0'){
                  parentId = '0';
                  return;
                }
              });
              if(parentId=='0'){
                this.parentOrgList = [{id:'0',orgName:'陕西瑞亚'}];
                res.data.forEach(v => {
                  this.parentOrgList.push(v);
                });
              }else{
                this.parentOrgList = res.data;
              }
            }
          }).catch(err => {
          })
        }
      },
      //获取机构列表
      getOrgList() {
        let url = urlSource.apiUrl + "org/queryOrg";
        this.$http.post(url,{id:this.$store.state.user.orgId,orgName : this.txtSearch}).then(res => {
          this.orgList = res.data;
          this.getCurrentParentOrg(this.$store.state.user.orgId);
        }).catch(err => {
        })
      },
      checkOrgCode(orgCode,id){
        if(orgCode!='' && orgCode!=undefined && orgCode!=null){
          let url = urlSource.apiUrl + 'org/checkOrgCode';
          let param = {orgCode:orgCode};
          param.id = id ? id : null;
          this.$http.post(url,param).then(res => {
            this.orgCodeError = res.data;
          }).catch(err => {
          })
        }else{
          this.orgCodeError = false;
        }

      },
      //打开新增机构
      openAddOrg() {
        this.modal.add.status = true;
        this.initAddOrg();
      },
      //初始化新增页面
      initAddOrg(){
        this.modal.add.form.id = '';
        this.modal.add.form.orgName = '';
        this.modal.add.form.orgCode = '';
        this.modal.add.form.parentId = '';
        this.modal.add.form.address = '';
        this.modal.add.form.remark = '';
      },
      /**
       * 修改机构
       */
      updateOrg() {
        let url = urlSource.apiUrl + "org/updateOrg";
        if (this.modal.update.form.createTime != "" && this.modal.update.form.createTime != null) {
          this.modal.update.form.createTime = new Date(this.modal.update.form.createTime);
        }
        this.$http.put(url, this.modal.update.form).then(res => {
          if (res.data) {
            this.modal.update.status = false;
            this.$Message.success("修改成功!")
            this.getOrgList();
            this.getCurrentParentOrg(this.$store.state.user.orgId);
          } else {
            this.$Message.error("修改失败!")
          }
        }).catch(err => {
          this.$Message.error("修改失败!")
        })
      },
      //添加机构
      addOrg() {
        let url = urlSource.apiUrl + "org/addOrg";
        this.$http.post(url, this.modal.add.form).then(res => {
          if (res.data) {
            this.$refs['modal.add.form'].resetFields();
            this.modal.add.status = false;
            this.$Message.success("新增成功!")
            this.getOrgList();
            this.getCurrentParentOrg(this.$store.state.user.orgId);
          } else {
            this.$Message.error("新增失败!")
          }
        }).catch(err => {
          this.$Message.error("新增失败!")
        })
      },
      deleteOrgBefore(row){
        let subUrl = urlSource.apiUrl + "org/getChildOrg/" + row.id;
        this.$http.get(subUrl).then(res => {
          if(res.data.length==0){
            this.modal.delete.status = true;
            this.modal.delete.orgName = row.orgName;
            this.modal.delete.id = row.id;
          }else{
              this.$Message.warning("该机构下存在子机构,请先删除子机构!")
          }

        }).catch(err => {
          this.$Message.error("删除失败!")
        });
      },
      //删除机构
      deleteOrg() {
        let url = urlSource.apiUrl + "org/deleteOrg/" + this.modal.delete.id;
        this.$http.delete(url).then(res => {
          if (res.data) {
            this.$Message.success("删除成功!")
            this.getOrgList();
            this.getCurrentParentOrg(this.$store.state.user.orgId);
            this.modal.delete.status = false;
          } else {
            this.$Message.error("删除失败!")
          }
        }).catch(err => {
          this.$Message.error("删除失败!")
        });
      }
    },
    mounted() {
      this.$nextTick(() => {
        /* 获取当前登录人的机构获取对应的上级机构 */
        this.getCurrentParentOrg(this.$store.state.user.orgId);
        this.getOrgList();
      })
    }
  }
</script>

<style lang="less">
  .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .ivu-modal {
    top: 2px;
  }
  .codeLb{
    position: absolute;
    padding-top: 6px;
    line-height: 1;
    color: #ed3f14;
    top: 100%;
    left: 0;
  }
</style>
